package com.thinkcube.edutainment.fragment;

import java.util.ArrayList;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.Trace;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.androidannotations.annotations.sharedpreferences.Pref;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.thinkcube.edutainment.EdutainmentConstant;
import com.thinkcube.edutainment.PaymentActivity_;
import com.thinkcube.edutainment.R;
import com.thinkcube.edutainment.ReachabilityTest;
import com.thinkcube.edutainment.Util;
import com.thinkcube.edutainment.adapters.LessonAdapter;
import com.thinkcube.edutainment.client.CourseClient;
import com.thinkcube.edutainment.client.LessonClient;
import com.thinkcube.edutainment.client.UserClient;
import com.thinkcube.edutainment.domain.Lesson;
import com.thinkcube.edutainment.domain.MetaData;
import com.thinkcube.edutainment.domain.OAuth;
import com.thinkcube.edutainment.domain.data.CourseData;
import com.thinkcube.edutainment.domain.data.LessonData;
import com.thinkcube.edutainment.domain.dto.CourseDto;
import com.thinkcube.edutainment.domain.dto.OAuthDto;
import com.thinkcube.edutainment.service.SPreferences_;

/**
 * MesithW @Cyberlmj 2:21:35 PM Email: shanuka.gayashan@cyberlmj.com
 */

@EFragment(R.layout.course_view)
public class CourseViewFragment extends Fragment implements
		OnItemClickListener, OnClickListener {

	CourseData courseData;

	@ViewById(R.id.course_name)
	TextView courseName;

	@ViewById(R.id.course_title_de)
	TextView courseTitle;

	@ViewById(R.id.course_description)
	TextView courseDescription;

	@ViewById(R.id.student_cunt_de)
	TextView studentCount;

	@ViewById(R.id.course_price_de)
	TextView coursePrice;

	@ViewById(R.id.author_title_de)
	TextView authorName;

	@ViewById(R.id.list)
	ListView listview;

	@ViewById(R.id.course_detail_view_icon)
	ImageView courseIcon;

	@ViewById(R.id.ratingbar_course_detail)
	RatingBar ratingBar;
	@ViewById(R.id.progressBar)
	ProgressBar dialog;

	@ViewById(R.id.other_courses)
	Button otherCourses;

	@ViewById(R.id.buy)
	Button buy;

	@ViewById(R.id.author_position)
	TextView authorTitle;

	@ViewById(R.id.priview)
	Button preview;

	@ViewById(R.id.add_wish_list)
	Button add_wish_list;

	ArrayList<LessonData> lessonsList;

	DisplayImageOptions options;
	ImageLoader imageLoader;

	private Boolean addWishList;

	public static CourseViewFragment newInstance(CourseData course) {
		CourseViewFragment fragment = new CourseViewFragment_();
		Bundle args = new Bundle();
		args.putParcelable("course", course);
		fragment.setArguments(args);
		return fragment;
	}

	public CourseViewFragment() {
		// Required empty public constructor
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.icon)
				.showImageForEmptyUri(R.drawable.icon)
				.showImageOnFail(R.drawable.icon).cacheOnDisc(true)
				.displayer(new RoundedBitmapDisplayer(5)).build();
		imageLoader = ImageLoader.getInstance();

		if (getArguments().containsKey("course")) {

			courseData = getArguments().getParcelable("course");

		}

	}

	@Trace
	@AfterViews
	void iniUi() {
		System.out.println("ini " + courseData.getIsCoursePurchased());

		courseTitle.setText(courseData.getCourseTitle());
		courseTitle.setTextSize(Util.pixelsToSp(getActivity()
				.getApplicationContext(), 48));

		courseDescription.setText(courseData.getCourseDescription());
		authorTitle.setText(courseData.getTeacherDescription());
		studentCount.setText(courseData.getNumOfStudents());
		coursePrice.setText(courseData.getCourseDisplayPrice());
		authorName.setText(courseData.getTeacherFullName());
		imageLoader.displayImage(courseData.getCourseIconLarge(), courseIcon,
				options);

		if (courseData.getCourseRating() != null) {
			ratingBar
					.setRating(Float.valueOf(courseData.getCourseRating()) / 2);
		}

		if (courseData.getIsCoursePurchased() != null) {
			if (courseData.getIsCoursePurchased().equals("true")) {
				buy.setText("Go To Course");
				buy.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						accessLesson(0);
					}
				});
			} else {
				buy.setOnClickListener(this);
			}
		}
		otherCourses.setOnClickListener(this);

		preview.setOnClickListener(this);

		// if(courseData.getHasWishList()!=null)
		if ((courseData.getHasWishList() != null)
				&& (courseData.getHasWishList().equals("true"))) {
			add_wish_list.setText("        Remove from Wishlist");
		} else {
			add_wish_list.setText("Add to Wishlist");
			// add_wish_list.setBackground(getResources().getDrawable(R.drawable.complete_btn_selector));
			// add_wish_list.setBackgroundResource(getResources().getDrawable(R.drawable.complete_btn_selector));
			add_wish_list
					.setBackgroundResource(R.drawable.complete_btn_selector);
		}

		addWishList = Boolean.valueOf(courseData.getHasWishList());

		gettoken(courseData);
	}

	@RestService
	LessonClient lessonClient;

	@RestService
	UserClient userClient;
	@RestService
	CourseClient courseClient;

	@Bean
	CourseDto courseDto;
	@Bean
	OAuthDto oAuthDto;

	@Pref
	SPreferences_ pref;

	@Background
	void gettoken(final CourseData courseData2) {
		oAuthDto.setAppId(EdutainmentConstant.APP_ID);
		oAuthDto.setAppSecret(EdutainmentConstant.APP_SCRET);

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					setTokenUi(courseData2, userClient.getRequestToken(oAuthDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
	}

	String user_token;

	void setTokenUi(CourseData courseData2, OAuth requestToken) {
		user_token = requestToken.getoAuth().getToken();
		getLesson(courseData2, requestToken);
	}

	@Trace
	@Background
	void getLesson(CourseData courseData2, OAuth requestToken) {

		courseDto.setAuthToken(requestToken.getoAuth().getToken());

		courseDto.setCourseId(courseData2.getCourseId());

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					doUi(lessonClient.getLesson(courseDto.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});

	}

	@Bean
	LessonAdapter lessonAdapter;

	@UiThread
	void doUi(Lesson lesson) {

		if (lesson != null) {
			if (lesson.getLessonList() != null) {

				lessonAdapter.setLessonData(lesson.getLessonList());

				if (courseData.getIsCoursePurchased() != null) {
					if (courseData.getIsCoursePurchased().equals("true")) {
						lessonAdapter.setCoursePurchase(true);
					} else {
						lessonAdapter.setCoursePurchase(false);
					}
				}

				listview.setAdapter(lessonAdapter);

				lessonsList = (ArrayList<LessonData>) lesson.getLessonList();

				listview.setOnItemClickListener(this);
			}
			dialog.setVisibility(View.GONE);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterview, View view,
			int position, long arg3) {

		System.out.println("----------------------------------------------");

		System.out.println("IS COURSE PURCHASE  >>>>>> "
				+ courseData.getIsCoursePurchased());

		System.out.println("COURSE Id  >>>>>> " + courseData.getCourseId());

		System.out.println("IS LESSON FREEE >>>>>> "
				+ lessonsList.get(position).getLessonFree());

		System.out.println("IS LESSON PURCHASE >>>>>> "
				+ lessonsList.get(position).getIs_lesson_purchased());

		System.out.println("LESON TYPE >>>>>>> "
				+ lessonsList.get(position).getLessonType());
		System.out.println("LESON Price >>>>>>> "
				+ lessonsList.get(position).getLessonPrice());

		System.out.println("----------------------------------------------");

		int type = Integer.valueOf(lessonsList.get(position).getLessonType());

		switch (type) {
		case 0:

			accessLesson(position);

			break;

		case 1:

			if (courseData.getIsCoursePurchased() != null) {
				if ((courseData.getIsCoursePurchased().equals("true"))
						|| (lessonsList.get(position).getIs_lesson_purchased()
								.equals("true"))) {
					accessLesson(position);
				} else {
					if (lessonsList.get(position).getLessonPrice().equals("0")) {
						showMessge(getString(R.string.lesson_access2));
					} else {
						showMessge(getString(R.string.lesson_access));
					}

				}
			}

			break;

		case 2:

			if (lessonsList.get(position).getIs_lesson_purchased()
					.equals("true")) {
				accessLesson(position);
			} else {

				showMessge(getString(R.string.lesson_access));
			}

			break;

		default:
			break;
		}

	}

	@Click({ R.id.other_courses, R.id.buy, R.id.priview, R.id.add_wish_list })
	public void onClick(View v) {

		System.out.println("TEACHER ID " + courseData.getTeacherId());

		switch (v.getId()) {
		case R.id.other_courses:

			otherCoursesClick();

			break;

		case R.id.buy:

			buyClick();

			break;
		case R.id.priview:

			previewClick();

			break;
		case R.id.add_wish_list:
			System.out.println("courseData.getHasWishList() "
					+ courseData.getHasWishList());
			if (addWishList) {
				removeFromWishList();
			} else {
				addToWishList();
			}

			break;

		default:
			break;
		}

	}

	@Trace
	@Background
	void addToWishList() {

		courseDto.setAuthToken(user_token);

		courseDto.setUserId(pref.getId().get());

		courseDto.setCourseId(courseData.getCourseId());

		courseDto.setAdd_to_list("1");

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					removedFromList(courseClient.getAddToWishList(courseDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("Not connected ");
			}
		});
	}

	@UiThread
	void removedFromList(MetaData metaData) {
		if (metaData.getStatus().equals("true")) {
			showMessge(metaData.getMessageText());
			addWishList = !addWishList;

			add_wish_list.setText("        Remove from Wishlist");

		}
	}

	@UiThread
	void addtoList(MetaData metaData) {
		if (metaData.getStatus().equals("true")) {
			showMessge(metaData.getMessageText());
			addWishList = !addWishList;
			add_wish_list.setText("Add to Wishlist");
			add_wish_list
					.setBackgroundResource(R.drawable.complete_btn_selector);

		}
	}

	@UiThread
	void wishListOut(MetaData metaData) {

		showMessge(metaData.getMessageText());
	}

	@Trace
	@Background
	void removeFromWishList() {
		courseDto.setAuthToken(user_token);

		courseDto.setUserId(pref.getId().get());

		courseDto.setCourseId(courseData.getCourseId());

		courseDto.setAdd_to_list("0");

		new ReachabilityTest(getActivity(), new ReachabilityTest.Callback() {

			@Override
			public void onReachabilityTestPassed() {

				try {
					addtoList(courseClient.getAddToWishList(courseDto
							.getMultiValuedMap()));
				} catch (Exception e) {

					System.err.println(e);
				}
			}

			@Override
			public void onReachabilityTestFailed() {

				showMessge("not connected ");
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 1) {

		}
	}

	void otherCoursesClick() {
		if (courseData.getTeacherId() != null) {

			FragmentTransaction fragmentTransaction = getFragmentManager()
					.beginTransaction();
			fragmentTransaction.replace(R.id.myfragment,
					TeacherProfile.newInstance(courseData.getTeacherId()));
			fragmentTransaction.commit();
		}
	}

	void buyClick() {
		Intent intent = new Intent(getActivity(), PaymentActivity_.class);
		intent.putExtra("courseObject", courseData);
		intent.putExtra("paymentData", courseData.getPaymentData());

		startActivityForResult(intent, 1);
	}

	void previewClick() {

		System.out.println("Preview URL "
				+ courseData.getCoursePreviewVedioUrl());
		String preVideoPath = courseData.getCoursePreviewVedioUrl();
		VideoFragment vidioPreview = new VideoFragment_();
		Bundle bundle = new Bundle();
		bundle.putBoolean("Preview", true);
		bundle.putString("Url", preVideoPath);
		vidioPreview.setArguments(bundle);
		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();
		fragmentTransaction.replace(R.id.rel1, vidioPreview).addToBackStack(
				null);
		fragmentTransaction.commit();

	}

	void accessLesson(int position) {

		FragmentTransaction fragmentTransaction = getFragmentManager()
				.beginTransaction();

		Bundle bundle = new Bundle();
		if ((lessonsList != null) && (lessonsList.size() > 0)) {
			bundle.putParcelable("lessonContents", lessonsList.get(position));
		}
		bundle.putInt("pos", position);

		bundle.putParcelable("course", courseData);

		FollowCourseFragment followCourse = new FollowCourseFragment();

		followCourse.setArguments(bundle);

		fragmentTransaction.replace(R.id.myfragment, followCourse);

		fragmentTransaction.addToBackStack(null);

		fragmentTransaction.commit();

	}

}
